package servlet.DeviceServlet;

import dao.DeviceDao;
import entity.DeviceBean;
import javax.servlet.annotation.WebServlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/deviceEdit")
public class DeviceEditServlet extends HttpServlet {
    public DeviceEditServlet() {
        super();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String optype = req.getParameter("optype");
        DeviceBean device = null;

        if ("add".equals(optype)) {
            device = new DeviceBean();
            device.setId(0);
            req.setAttribute("device", device);
            req.getRequestDispatcher("device_edit.jsp").forward(req, resp);
        } else if ("edit".equals(optype)) {
            DeviceDao dao = new DeviceDao();
            String id = req.getParameter("id");
            device = dao.editFindDevice(id);
            req.setAttribute("device", device);
            req.getRequestDispatcher("device_edit.jsp").forward(req, resp);
        } else if ("delete".equals(optype)) {
            DeviceDao dao = new DeviceDao();
            String id = req.getParameter("id");
            int res = dao.deleteDevice(id);
            PrintWriter out = resp.getWriter();
            if (res > 0) {
                out.println("删除数据成功");
                req.getRequestDispatcher("deviceList").forward(req, resp);
            } else {
                out.println("删除数据失败");
                resp.setHeader("refresh", "3;deviceList");
            }
        } else {
            throw new IllegalArgumentException("出错了，非法操作！");
        }

    }

    @Override
    public void destroy() {
        super.destroy();
    }
}
